package com.sahala.downimage.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class SplitFile {

	private static String path = "E:\\pic\\20120709";

	public static void main(String[] args) {
		try {
			move(getFiles());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static File[] getFiles() {
		File dir = new File(path);
		if (dir.isDirectory()) {
			File[] files = dir.listFiles();
			return files;
		}
		return null;
	}

	private static void move(File[] files) {
		int dirNum = 1;
		File firstDir = new File(path + File.separator + dirNum);
		if (!firstDir.exists()) {
			firstDir.mkdir();
		}
		for (int i = 0, j = files.length; i < j; i++) {
			File file = files[i];
			FileInputStream input = null;
			FileOutputStream out = null;
			try {
				input = new FileInputStream(file);

				out = new FileOutputStream(new File(path + File.separator
						+ dirNum)
						+ File.separator + file.getName());

				FileChannel fcin = input.getChannel();
				FileChannel fcout = out.getChannel();
				ByteBuffer buffer = ByteBuffer.allocate(1024);
				while (true) {
					buffer.clear();
					int r = fcin.read(buffer);
					if (r == -1) {
						break;
					}
					buffer.flip();
					fcout.write(buffer);
				}
				if ((i + 1) % 100 == 0) {
					dirNum++;
					new File(path + File.separator + dirNum).mkdir();
					System.out.println(dirNum + " start");
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					input.close();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			file.delete();
		}
	}
}
